<template>
  <div class="poster-base section-base">
    <div class="poster-base-up">
      <div class="sample-title">可选海报背景</div>
      <div class="sample-list">
        <template v-for="(item, index) in sample_bg_img">
          <div class="sample-item">
            <img @click="selectImg(item)" :src="item" alt="" width="100%">
            <div v-if="item == poster_config.bgImg" class="item-selected">
              <img src="../../../assets/images/activity/poster/icon_check.png" alt="" width="100%" height="100%"/>
            </div>
          </div>
        </template>
      </div>
    </div>
    <div class="poster-base-down">
      <div id="rightDiv" class="rightDiv">
        <canvas id="fabric" style="border: 1px dashed #000000;"></canvas>
      </div>
      <div class="function-region-base">
        <div class="function-region-item">
          <el-button @click="editBgImg">自选背景上传</el-button>
        </div>
        <div class="function-region-item">
          <el-button @click="delTextBox" v-if="poster_config.textBox" type="danger">删除定义文本</el-button>
          <el-button @click="setTextBox" v-else>自定义文本项</el-button>
        </div>
        <div class="function-region-item">
          <el-button @click="delHeadBox" v-if="poster_config.headBox" type="danger">删除头像位置</el-button>
          <el-button @click="setHeadBox" v-else>添加头像位置</el-button>
        </div>
        <div class="function-region-item">
          <el-button @click="delNickBox" v-if="poster_config.nickBox" type="danger">删除昵称位置</el-button>
          <el-button @click="setNickBox" v-else>添加昵称位置</el-button>
        </div>
        <div class="function-region-item">
          <el-button @click="savePoster" type="primary">应用海报</el-button>
        </div>
      </div>
    </div>
    <el-dialog title="图片裁剪" :visible.sync="open" width="700px" append-to-body @opened="modalOpened"  @close="closeDialog">
      <el-row>
        <el-col :xs="24" :md="24" :style="{height: '500px'}">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="false"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :fixed="options.fixed"
            :fixed-number="options.fixedNumber"
            :outputType="options.outputType"
            :outputSize="1"
            :full="true"
            :original="false"
            :infoTrue="true"
            :high="true"
            @realTime="realTime"
            v-if="visible"
          />
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :sm="3" :xs="3">
          <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
            <el-button size="small">
              选择
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{span: 2, offset: 6}" :sm="2" :xs="2">
          <el-button type="primary" size="small" @click="uploadImg()">选 中</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { fabric } from 'fabric'
import BtnSingleImageUpload from '@/components/BtnSingleImageUpload'
import { debounce } from "@/utils";
import store from "@/store";
import { VueCropper } from "vue-cropper";
import { uploadFile } from "@/api/system/user";
import { activityPosterConfig,updatePosterConfig } from "@/api/triones/activity";
export default {
  name: "poster",
  components: { BtnSingleImageUpload, VueCropper },
  data() {
    return {
      /** 示例背景图 */
      sample_bg_img: [
        'https://yueshangxuan.oss-cn-chengdu.aliyuncs.com/yjj/normal/295f375e322660593f14ee312b85a4a5c9d9285c27c077432454129aad16bda1.jpg',
        'https://yueshangxuan.oss-cn-chengdu.aliyuncs.com/yjj/normal/e5e055c04ac27d198e777aa428984b1a90b3cb83d789e60c3b7694c2eca0567c.jpg',
        'https://yueshangxuan.oss-cn-chengdu.aliyuncs.com/yjj/normal/4f58378a590a5f04d5c6145b707544a8b8a0999c443ac88fe68b4b400dfde90f.jpg'
      ],
      /** 画布属性 */
      canvas: null,
      poster_config: {
        bgImg: 'https://yueshangxuan.oss-cn-chengdu.aliyuncs.com/yjj/normal/295f375e322660593f14ee312b85a4a5c9d9285c27c077432454129aad16bda1.jpg',
        qrBox: null,
        qrBoxObj: {
          id: 'qr',
          top: 380,
          left: 180,
          radius: 50
          // width: 100,
          // height: 100,
        },
        headBox: null,
        headBoxObj: {
          id: 'head',
          top: 420,
          left: 10,
          width: 60,
          height: 60,
        },
        textBox: null,
        textBoxObj: {
          id: 'text',
          text: '请输入文本',
          top: 100,
          left: 40,
          width: 150,
          fontSize: 20
        },
        nickBox: null,
        nickBoxObj: {
          id: 'nick',
          top: 380,
          left: 20,
          width: 100,
          height: 22,
        }
      },
      /** 图片裁剪属性 */
      options: {
        //裁剪图片的地址
        img: store.getters.avatar,
        //是否默认生成截图框
        autoCrop: true,
        //固定截图框大小,不允许改变
        fixedBox: false,
        //默认生成截图为PNG格式
        outputType:"png",
        filename: '',
        //是否开启截图框宽高固定比例
        fixed: true,
        // 截图框的宽高比例
        fixedNumber: [3, 5]
      },
      cropperBoxHeight: '500px',
      previews: {},
      resizeHandler: null,
      visible: false,
      open: false,
    }
  },
  watch: {
    'poster_config.bgImg'(oldVal,newVal) {
      if (oldVal) {
        const container = document.getElementById('rightDiv');
        this.setBackground(container.clientWidth, container.clientHeight)
      }
    },
    deep: true,
    immediate: true
  },
  mounted() {
    this.getActivityPosterConfig();
  },

  methods: {
    /** 获取活动海报配置 */
    getActivityPosterConfig() {
      activityPosterConfig(this.$route.query.id).then(response => {
        if (response.data.poster_config) {
          this.poster_config = JSON.parse(response.data.poster_config);
        }
        this.$nextTick(() => {
          console.log('$route.query.id',this.$route.query.id)
          this.initCanvas();
        })
      })
    },
    /** 初始化canvas */
    initCanvas() {
      // 获取容器元素,得到父容器的宽和高
      const container = document.getElementById('rightDiv');
      // 创建一个与容器宽高一致的 canvas 对象
      this.canvas = new fabric.Canvas("fabric", {
        width: container.clientWidth,
        height: container.clientHeight,
        // 启用右键，button的数字为3
        fireRightClick: true,
        // 禁止默认右键菜单
        stopContextMenu: true,
        //拖拽、缩放背景不受影响
        backgroundVpt: false
      });
      // 设置画布的背景图片
      this.setBackground(container.clientWidth, container.clientHeight);
      //设置二维码圆形框
      this.setQrBox();
      if (this.poster_config.headBox) {
        this.setHeadBox();
      }
      if (this.poster_config.nickBox) {
        this.setNickBox();
      }
      if (this.poster_config.textBox) {
        this.setTextBox();
      }
    },
    /** 设置画布的背景图片 */
    setBackground(clientWidth, clientHeight) {
      fabric.Image.fromURL(this.poster_config.bgImg, img => {
        this.canvas.setBackgroundImage(img, this.canvas.renderAll.bind(this.canvas),{
          scaleX: this.canvas.width/img.width,
          scaleY: this.canvas.height/img.height,
          originX: 'left',
          originY: 'top'
        });
      });
      //隐藏旋转控制点和主体之间那条控制线
      fabric.Object.prototype.transparentCorners = false;
      //控制点的大小
      fabric.Object.prototype.cornerSize = 7;
      //旋转控制点距离边框控制点的偏移
      fabric.Object.prototype.controls.mtr.offsetY = 0;
    },
    /** 设置二维码存放的矩形框 */
    setQrBox: function () {
      const circle = new fabric.Circle({
        radius: this.poster_config.qrBoxObj.radius,
        fill: '#ffffff',
        originX: 'center',
        originY: 'center',
        strokeDashArray: [2, 2],
        stroke: '#000000',
        strokeWidth: 1
      });
      // const rect = new fabric.Rect({
      //   width: this.poster_config.qrBoxObj.width,
      //   height: this.poster_config.qrBoxObj.height,
      //   fill: '#ffffff',
      //   originX: 'center',
      //   originY: 'center',
      //   strokeDashArray: [2,2],
      //   stroke: '#000000',
      //   strokeWidth: 1
      // });

      const dsc = new fabric.Text('二维码', {
        fontSize: 14,
        originX: 'center',
        originY: 'bottom',
        fontWeight: 'bold'
      });
      const movable = new fabric.Text('（可拖动）', {
        fontSize: 10,
        originX: 'center',
        originY: 'top'
      });
      this.poster_config.qrBox = new fabric.Group([circle, dsc, movable], {
        id: this.poster_config.qrBoxObj.id,
        top: this.poster_config.qrBoxObj.top,
        left: this.poster_config.qrBoxObj.left,
        // width: this.poster_config.qrBoxObj.width,
        // height: this.poster_config.qrBoxObj.height,
        width: this.poster_config.qrBoxObj.radius * 2,
        height: this.poster_config.qrBoxObj.radius * 2,
        lockRotation: true
      });
      this.canvas.add(this.poster_config.qrBox);
      /** 隐藏上下左右中间控制点 */
      this.poster_config.qrBox.setControlsVisibility({
        ml: false,
        mb: false,
        mr: false,
        mt: false,
        mtr: false,
      });
      this.poster_config.qrBox.on('mouseup', ev => {
        console.log('ev',ev)
        this.boundary(ev);
      })
    },
    /** 设置头像圆形框 */
    setHeadBox() {
      const circle = new fabric.Circle({
        radius: 30,
        fill: '#ffffff',
        originX: 'center',
        originY: 'center',
        strokeDashArray: [2,2],
        stroke: '#000000',
        strokeWidth: 1
      });
      const dsc = new fabric.Text('头像', {
        fontSize: 14,
        originX: 'center',
        originY: 'bottom',
        fontWeight: 'bold'
      });
      const movable = new fabric.Text('（可拖动）', {
        fontSize: 10,
        originX: 'center',
        originY: 'top'
      });
      this.poster_config.headBox = new fabric.Group([circle, dsc,movable], {
        id: this.poster_config.headBoxObj.id,
        top: this.poster_config.headBoxObj.top,
        left: this.poster_config.headBoxObj.left,
        width: this.poster_config.headBoxObj.width,
        height: this.poster_config.headBoxObj.height,
        lockRotation: true,
        hasControls: false
      });
      this.canvas.add(this.poster_config.headBox);
      this.poster_config.headBox.on('mouseup', ev => {
        this.boundary(ev);
      })
    },
    /** 删除头像圆形框 */
    delHeadBox() {
      this.canvas.remove(this.poster_config.headBox);
      this.poster_config.headBox = null;
    },
    /** 设置昵称矩形框 */
    setNickBox() {
      const rect = new fabric.Rect({
        width: 100,
        height: 22,
        rx: 5,
        ry: 5,
        fill: '#ffffff',
        originX: 'center',
        originY: 'center',
        strokeDashArray: [2,2],
        stroke: '#000000',
        strokeWidth: 1
      });
      const dsc = new fabric.Text('昵称（可拖动）', {
        fontSize: 12,
        originX: 'center',
        originY: 'center'
      });
      this.poster_config.nickBox = new fabric.Group([rect, dsc], {
        id: this.poster_config.nickBoxObj.id,
        top: this.poster_config.nickBoxObj.top,
        left: this.poster_config.nickBoxObj.left,
        width: this.poster_config.nickBoxObj.width,
        height: this.poster_config.nickBoxObj.height,
        lockRotation: true,
        hasControls: false
      });
      this.canvas.add(this.poster_config.nickBox);
      this.poster_config.nickBox.on('mouseup', ev => {
        this.boundary(ev);
      })
    },
    /** 删除昵称位置 */
    delNickBox() {
      this.canvas.remove(this.poster_config.nickBox);
      this.poster_config.nickBox = null;
    },
    /** 设置文本 */
    setTextBox() {
      this.poster_config.textBox = new fabric.IText(this.poster_config.textBoxObj.text, {
        id: this.poster_config.textBoxObj.id,
        top: this.poster_config.textBoxObj.top,
        left: this.poster_config.textBoxObj.left,
        fontSize: this.poster_config.textBoxObj.fontSize,
        fontFamily: 'Arial',
        fill: '#000000',
        lockRotation: true,
        hasControls: false
      });
      //控制文本的手柄
      this.poster_config.textBox.setControlsVisibility({
        mt: false,
        mr: false,
        mb: false,
        ml: false,
      });
      this.canvas.add(this.poster_config.textBox);
      //活跃状态
      this.canvas.setActiveObject(this.poster_config.textBox);
      //进入编辑状态
      this.poster_config.textBox.enterEditing();
      //选中所有文本
      this.poster_config.textBox.selectAll();
      this.poster_config.textBox.on('mouseup', ev => {
        this.boundary(ev);
      });
    },
    /** 删除文本 */
    delTextBox() {
      this.canvas.remove(this.poster_config.textBox);
      this.poster_config.textBox = null;
    },
    /** 边界计算 */
    boundary(ev) {
      // 获取画布视口边界
      let canvasBoundaries = this.canvas.calcViewportBoundaries();
      // 矩形本身
      let obj = ev.target
      // 矩形的边界
      let objBoundingRect = obj.getBoundingRect()
      if (objBoundingRect.left < canvasBoundaries.tl.x) {
        ev.target.left = canvasBoundaries.tl.x
      }
      if (objBoundingRect.left + objBoundingRect.width > canvasBoundaries.br.x) {
        ev.target.left = canvasBoundaries.br.x - objBoundingRect.width
      }
      if (objBoundingRect.top < canvasBoundaries.tl.y) {
        ev.target.top = canvasBoundaries.tl.y
      }
      if (objBoundingRect.top + objBoundingRect.height > canvasBoundaries.br.y) {
        ev.target.top = canvasBoundaries.br.y - objBoundingRect.height
      }
      this.canvas.renderAll();
    },
    /** 编辑背景图片 */
    editBgImg() {
      this.open = true;
    },
    /** 打开弹出层结束时的回调 */
    modalOpened() {
      this.visible = true;
      if (!this.resizeHandler) {
        this.resizeHandler = debounce(() => {
          this.refresh()
        }, 100)
      }
      window.addEventListener("resize", this.resizeHandler)
    },
    /** 刷新组件 */
    refresh() {
      this.$refs.cropper.refresh();
    },
    /** 覆盖默认的上传行为 */
    requestUpload(file) {
      console.log('覆盖默认的上传行为')
      let reader = new FileReader()
      reader.readAsDataURL(file.file)
      reader.onload = e=>{
        const img = e.target.result;
        const image = new Image()
        image.src=img
        image.onload = _=>{
          let width = image.width
          let height= image.height
          this.cropperBoxHeight = image.height + 'px';
          console.log('width',width)
          console.log('height',height)
        }
      }
    },
    /** 上传预处理 */
    beforeUpload(file) {
      console.log('上传预处理',file)
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          console.log('上传预处理 - reader',reader)
          this.options.img = reader.result;
          this.options.filename = file.name;
        };
      }
    },
    /** 上传处理 */
    uploadImg() {
      this.$refs.cropper.getCropBlob((data) => {
        let formData = new FormData();
        console.log(this.options.filename)
        formData.append("file", data, this.options.filename);
        uploadFile(formData).then(response => {
          this.open = false;
          this.options.img = response.data.url;
          this.poster_config.bgImg = response.data.url;
          this.visible = false;
        });
      },
        {
          type: 'image/png',
          quality: 1,
        });
    },
    /** 实时预览 */
    realTime(data) {
      this.previews = data;
    },
    /** 关闭窗口 */
    closeDialog() {
      //设置默认的加载图片
      this.visible = false;
      window.removeEventListener("resize", this.resizeHandler)
    },
    /** 图片选中 */
    selectImg(url) {
      this.poster_config.bgImg = url;
    },
    /** 应用海报 */
    savePoster() {
      this.canvas.renderAll();
      const objects = this.canvas.getObjects();
      for (const objectsKey of objects) {
        console.log('id',objectsKey.get('id'))
        console.log('objectsKey',objectsKey)
        console.log('getBoundingRect',objectsKey.getBoundingRect())
        if (objectsKey.get('id') === 'qr') {
          this.poster_config.qrBoxObj.top = objectsKey.getBoundingRect().top;
          this.poster_config.qrBoxObj.left = objectsKey.getBoundingRect().left;
          // this.poster_config.qrBoxObj.width = objectsKey.getBoundingRect().width;
          // this.poster_config.qrBoxObj.height = objectsKey.getBoundingRect().height;
          this.poster_config.qrBoxObj.radius = objectsKey.getBoundingRect().width / 2;
        }
        if (objectsKey.get('id') === 'head') {
          this.poster_config.headBoxObj.top = objectsKey.getBoundingRect().top;
          this.poster_config.headBoxObj.left = objectsKey.getBoundingRect().left;
          this.poster_config.headBoxObj.width = objectsKey.getBoundingRect().width;
          this.poster_config.headBoxObj.height = objectsKey.getBoundingRect().height;
        }
        if (objectsKey.get('id') === 'text') {
          this.poster_config.textBoxObj.text = objectsKey.text;
          this.poster_config.textBoxObj.top = objectsKey.getBoundingRect().top;
          this.poster_config.textBoxObj.left = objectsKey.getBoundingRect().left;
          this.poster_config.textBoxObj.width = objectsKey.getBoundingRect().width;
        }
        if (objectsKey.get('id') === 'nick') {
          this.poster_config.nickBoxObj.top = objectsKey.getBoundingRect().top;
          this.poster_config.nickBoxObj.left = objectsKey.getBoundingRect().left;
          this.poster_config.nickBoxObj.width = objectsKey.getBoundingRect().width;
          this.poster_config.nickBoxObj.height = objectsKey.getBoundingRect().height;
        }
      }
      const data = {
        activityId: this.$route.query.id,
        posterConfig: JSON.stringify(this.poster_config)
      }
      updatePosterConfig(data).then(response =>{
      this.$store.dispatch("tagsView/delView", this.$route);
        this.$router.go(-1);
      })
    }
  }
}
</script>

<style scoped lang="scss">
.section-base {
  overflow-x: auto;
  padding-bottom: 50px;
}

.poster-base {
  .poster-base-up {
    width: 100%;
    height: 240px;
    padding: 20px;
    margin-bottom: 20px;
    .sample-title {
      height: 20px;
      font-weight: bold;
    }
    .sample-list {
      padding-top: 20px;
      width: 100%;
      display: flex;
      justify-content: start;
      .sample-item {
        position: relative;
        margin-right: 20px;
        width: 90px;
        .item-selected {
          width: 20px;
          height: 20px;
          position: absolute;
          top: -10px;
          left: 80px;
        }
        img:hover {
          cursor: pointer;
        }
      }
    }
  }
  .poster-base-down {
    display: flex;
    justify-content: center;
    .rightDiv {
      display: flex;
      justify-content: center;
      width: 300px;
      height: 500px;
    }

    .function-region-base {
      margin-left: 20px;
      width: 200px;
      height: 500px;
      text-align: center;
      .function-region-item {
        padding-bottom: 20px;
      }
      .concise-item {
        box-sizing: border-box;
        width: 100%;
        .concise-item-image-btn {
          display: flex;
          .btn {
            position: relative;
            display: flex;
            align-items: center;
            line-height: 36px;
            color: #fff;
            font-size: 16px;
            text-align: center;
            border-radius: 3px;
            background: rgba(73, 73, 73);
            padding: 0 10px;
            cursor: pointer;
            box-sizing: border-box;
            .icon-upload {
              width: 16px;
              height: 16px;
              background-repeat: no-repeat;
              background-position: 50%;
              background-image: url('~@/assets/images/activity/icon_upload.png');
              background-size: contain;
              margin-right: 6px;
            }
          }
        }
      }
    }
  }
}

.avatar-upload {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 300px;
  height: 500px;
  box-shadow: 0 0 4px #ccc;
  overflow: hidden;
}
</style>
